package com.xyy.saas.payment.merchant.core.service;

import com.alibaba.fastjson.JSONObject;
import com.xyy.saas.payment.api.impl.PaymentMerchantApiImpl;
import com.xyy.saas.payment.cores.enums.*;
import com.xyy.saas.payment.cores.vo.OpenAccountVO;
import com.xyy.saas.payment.cores.vo.ResultVO;
import com.xyy.saas.payment.dao.model.ApplyOpenAccountStatus;
import com.xyy.saas.payment.dao.model.ApplypayUserInfo;
import com.xyy.saas.payment.dao.model.OpenpayInfo;
import com.xyy.saas.payment.dao.model.ThirdUserInfo;
import com.xyy.saas.payment.merchant.core.dto.AccountDto;
import com.xyy.saas.payment.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * 聚合支付开户
 */
@Service
@Slf4j
public class AccountService {
    @Resource
    private PaymentMerchantApiImpl paymentMerchantApi;
    @Resource
    private PayAccountService payAccountService;
    @Autowired
    private ThirdUserInfoService thirdUserInfoService;
    @Autowired
    private ApplyOpenAccountStatusService applyOpenAccountStatusService;
    @Autowired
    private OpenpayInfoService openpayInfoService;
    @Autowired
    private ApplypayUserInfoService applypayUserInfoService;
    @Resource
    private ApplyBankcardService applyBankcardService;

    /**
     * 1.开户
     * 2.绑卡
     */
    public ResultVO createAccount(AccountDto accountDto, String sign) throws Exception {
        log.info("AccountService#createAccount accountDto：{}, sign：{}", JSONObject.toJSONString(accountDto), sign);

        // 0.参数校验
        accountDto.checkParam();

        // 若为买家 且 重发短信，则不进行开户处理
        if (null != accountDto.getResendCode() && accountDto.getResendCode() == 1 && CustomerTypeEnum.BUYER.getType().equals(accountDto.getCustomerType())) {
            log.info("AccountService#createAccount accountDto(重发短信，不进行开户操作处理)：{}", JSONObject.toJSONString(accountDto));
        } else {
            // 1.开户
            ResultVO result = paymentMerchantApi.merchantCertifyAccountCreate(accountDto.buildMerchantAccountCreateVo(), sign);
            if (!Objects.equals(result.getCode(), ResultCodeEnum.SUCCESS.getCode()) && !Objects.equals(result.getCode(), ResultCodeEnum.ACCOUNT_IS_EXIST.getCode())) {
                return result;
            }
        }

        // 填充支付平台用户信息
        String accountId = payAccountService.getAccountIdByBusiness(accountDto.getBusinessIdType(), accountDto.getBusinessId());
        accountDto.setUserId(accountId);

        // EC 且为 买家，则进行解绑操作
        boolean unBind = false;
        if (accountDto.getBusinessIdType().toUpperCase().contains("EC") && CustomerTypeEnum.BUYER.getType().equals(accountDto.getCustomerType())) {
            unBind = true;
        }

        // 2.绑卡
        applyBankcardService.apply(accountDto.buildApplyBankcardModifyDto(), unBind);

        // 3.返回响应
        OpenAccountVO openAccountVO = new OpenAccountVO();
        openAccountVO.setApplymentNo(accountId);
        return ResultVO.createSuccess(openAccountVO);
    }

    /**
     * 校验用户是否开基本户户成功
     */
    public boolean checkBaseOpenAccountComplete(String accountId) {
        ThirdUserInfo thirdUserInfo = thirdUserInfoService.getThirdUserInfoByUserId(accountId);
        return thirdUserInfo != null && !thirdUserInfo.getUserId().equals(thirdUserInfo.getThirdUserId());
    }

    /**
     * 校验用户是否开户成功 流程走完+富民开通支付功能配置完成
     */
    public boolean checkOpenAccountComplete(String accountId) {
        try {
            ThirdUserInfo thirdUserInfo = thirdUserInfoService.getThirdUserInfoByUserId(accountId);

            if(thirdUserInfo == null || thirdUserInfo.getUserId().equals(thirdUserInfo.getThirdUserId())) {
                return false;
            }

            // 查询微信开户意愿申请单
            ApplyOpenAccountStatus queryParam = new ApplyOpenAccountStatus();
            queryParam.setAccountId(accountId);
            queryParam.setThirdUserId(thirdUserInfo.getThirdUserId());
            List<ApplyOpenAccountStatus> applyOpenAccountStatuses = applyOpenAccountStatusService.selectByParam(queryParam);

            if(applyOpenAccountStatuses.size() != 1) {
                return false;
            }

            // 未授权代表开户未完成
            ApplyOpenAccountStatus applyOpenAccountStatus = applyOpenAccountStatuses.get(0);

            if(applyOpenAccountStatus.getAuthorize() != OpenAccountAuthorizeStatusEnum.AUTHORIZE_STATE_AUTHORIZED.getStatus()) {
                return false;
            }

            // 查询支付功能
            ApplypayUserInfo applypayUserInfo = applypayUserInfoService.queryUserInfoByAccountId(accountId);
            List<OpenpayInfo> openpayInfos = openpayInfoService.queryUserInfoByAccountId(accountId, applypayUserInfo.getThirdUserInfoId());

            for(OpenpayInfo openpayInfo : openpayInfos) {
                if(FBankPowerIdEnum.WX_MINI.getPowerId().equals(openpayInfo.getPowerId())
                        || FBankPowerIdEnum.WX_OFFICIAL.getPowerId().equals(openpayInfo.getPowerId()))
                {
                    if(!OpenPayStatusEnum.SUCCESS_PAY_CHANNEL.getStatus().equals(openpayInfo.getStatus())) {
                        // 如果富民配置没完成 算开户未成功
                        return false;
                    }
                }
            }

            return true;
        }
        catch(Exception ex) {
            log.error(ex.getMessage(), ex);
            return false;
        }
    }

    /**
     * 检查用户是否处于待法人扫码
     */
    public boolean checkOpenAccountWaitAuth(String accountId) {
        ThirdUserInfo thirdUserInfo = thirdUserInfoService.getThirdUserInfoByUserId(accountId);

        if(thirdUserInfo == null || thirdUserInfo.getUserId().equals(thirdUserInfo.getThirdUserId())) {
            return false;
        }

        // 查询微信开户意愿申请单
        ApplyOpenAccountStatus queryParam = new ApplyOpenAccountStatus();
        queryParam.setAccountId(accountId);
        queryParam.setThirdUserId(thirdUserInfo.getThirdUserId());
        List<ApplyOpenAccountStatus> applyOpenAccountStatuses = applyOpenAccountStatusService.selectByParam(queryParam);

        if(applyOpenAccountStatuses.size() != 1) {
            return false;
        }

        ApplyOpenAccountStatus status = applyOpenAccountStatuses.get(0);

        // 微信开户意愿审核通过 && 法人未扫码
        return status.getAuthorize() != OpenAccountAuthorizeStatusEnum.AUTHORIZE_STATE_AUTHORIZED.getStatus() &&
                (OpenAccountApplyStatusEnum.APPLYMENT_STATE_WAITTING_FOR_CONFIRM_CONTACT.getStatus() == status.getStatus() ||
                        OpenAccountApplyStatusEnum.APPLYMENT_STATE_WAITTING_FOR_CONFIRM_LEGALPERSON.getStatus() == status.getStatus() ||
                        OpenAccountApplyStatusEnum.APPLYMENT_STATE_PASSED.getStatus() == status.getStatus() ||
                        OpenAccountApplyStatusEnum.APPLYMENT_STATE_FREEZED.getStatus() == status.getStatus());
    }

    /**
     * 检查用户是否处于待法人扫码
     */
    public boolean checkOpenAccountWaitAudit(String accountId) {
        ThirdUserInfo thirdUserInfo = thirdUserInfoService.getThirdUserInfoByUserId(accountId);

        if(thirdUserInfo == null || thirdUserInfo.getUserId().equals(thirdUserInfo.getThirdUserId())) {
            return false;
        }

        // 查询微信开户意愿申请单
        ApplyOpenAccountStatus queryParam = new ApplyOpenAccountStatus();
        queryParam.setAccountId(accountId);
        queryParam.setThirdUserId(thirdUserInfo.getThirdUserId());
        List<ApplyOpenAccountStatus> applyOpenAccountStatuses = applyOpenAccountStatusService.selectByParam(queryParam);

        if(applyOpenAccountStatuses.size() != 1) {
            return false;
        }

        ApplyOpenAccountStatus status = applyOpenAccountStatuses.get(0);

        // 开户意愿申请等待审核 || 申请被驳回
        return status.getAuthorize() != OpenAccountAuthorizeStatusEnum.AUTHORIZE_STATE_AUTHORIZED.getStatus() &&
                (OpenAccountApplyStatusEnum.APPLYMENT_STATE_WAITTING_FOR_AUDIT.getStatus() == status.getStatus() ||
                        OpenAccountApplyStatusEnum.APPLYMENT_STATE_CANCELED.getStatus() == status.getStatus());
    }
}